package com.glodon.interceptor;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


/**
 * @author geloin
 * @date 2012-3-27 下午2:29:35
 */
@Repository
public class SystemInterceptor extends HandlerInterceptorAdapter {


    /*
     * (non-Javadoc)
     *
     * @see
     * org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle
     * (javax.servlet.http.HttpServletRequest,
     * javax.servlet.http.HttpServletResponse, java.lang.Object)
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {

        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String requestType = request.getHeader("X-Requested-With");
        //System.out.println("+++++++++++++++++++++++reqestType:" + requestType);
        // 后台session控制
        String[] noFilters = new String[]{"login.jsp", "login", "assets"};
        String uri = request.getRequestURI();
        //System.out.println("+++++++++++++++++++++++uri:" + uri);
        boolean beFilter = true;
        for (String s : noFilters) {
            if (uri.indexOf(s) != -1) {
                beFilter = false;
                break;
            }
        }
        if (beFilter) {
            Object obj = request.getSession().getAttribute("username");
            if (null == obj) {
                if (StringUtils.isNotBlank(requestType) && requestType.equalsIgnoreCase("XMLHttpRequest")) {
                    response.setHeader("sessionstatus", "timeout");
                    response.sendError(518, "session timeout.");
                    return false;
                } else {
                    // 未登录
                    PrintWriter out = response.getWriter();
                    StringBuilder builder = new StringBuilder();
                    builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
                    builder.append("window.top.location.href=\"");
                    builder.append("/login.jsp\";</script>");
                    out.print(builder.toString());
                    out.close();
                    return false;
                }
            }
        }
        return super.preHandle(request, response, handler);
    }

}